package top.withwings.bonus.common.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.withwings.bonus.common.pojo.IndexedGrantedAuthority;
import top.withwings.bonus.common.pojo.User;
import top.withwings.bonus.common.service.UserService;

import java.util.Collections;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("all")
    public List<User> getUsers(){
        return userService.findAll();
    }


    @PostMapping("enable")
    public void enable(int userId){

        User user = userService.findById(userId);
        user.setEnabled(true);
        userService.update(user);

    }

    @PostMapping("disable")
    public void disable(int userId){

        User user = userService.findById(userId);
        user.setEnabled(false);
        userService.update(user);

    }

    @PostMapping("update")
    public void update(int id, String username,String realname){

        User user = userService.findById(id);
        user.setUsername(username);
        user.setRealname(realname);
        userService.update(user);

    }

    @PostMapping("create")
    public void create(String username,String realname){

        User user = new User();
        user.setUsername(username);
        user.setRealname(realname);
        IndexedGrantedAuthority defaultAuthority= new IndexedGrantedAuthority();
        defaultAuthority.setIndex(2);
        defaultAuthority.setAuthority("ROLE_SALESMAN");
        user.setAuthorities(Collections.singletonList(defaultAuthority));
        userService.create(user);

    }

    @PostMapping("delete")
    public void delete(int id){

        User user = userService.findById(id);

        userService.delete(id);

    }

}
